package org.nashua.toughtechs151.dash;

import java.util.Timer;

public abstract class Connection {
	private ConnectionListener listener;
	protected Timer t = new Timer();
        protected String[][] str = new String[0][0];
	public void setConnectionListener(ConnectionListener cl){
            listener=cl;
	}
	protected void onConnect() {
            listener.onConnect();
	}
	protected void onDisconnect() {
            listener.onDisconnect();
	}
	protected void onDataRecieved(String str){
            if (str.startsWith("RETURN")) {
                update(str.substring(str.indexOf(",")+1,str.indexOf("&")),str.substring(str.indexOf("&")+1));
            } else {
                listener.onDataRecieved(str);
            }
	}
	public abstract void sendData(String str);
	public abstract void disconnect();

        public String requestData(String req) {
            String stri=null;
            while ((stri=grab(req))==null) {System.out.println("Waiting");}
            return stri;
        }
        public String grab(String key) {
            for (int i=0;i<str.length;i++)
                if (str[i][0].equals(key))
                    return str[i][1];
            return null;
        }
        public void update(String key,String value) {
            for (int i=0;i<str.length;i++) {
                if (str[i][0].equals(key)) {
                    if (value==null) {
                        str[i]=null;
                        clean();
                    } else {
                        str[i][1]=value;
                    }
                    return;
                }
            }
            add(key,value);
        }
        public void add(String key, String value){
            clean();
            String[][] strr = new String[str.length+1][2];
            for (int i=0;i<str.length;i++) strr[i]=str[i];
            strr[str.length] = new String[]{key,value};
            str=strr;
        }
        public void clean() {
            int c=0;
            for (int i=0;i<str.length;i++) c+=str[i]!=null?1:0;
            String[][] strr = new String[c][2];
            int x=0;
            for (int i=0;i<str.length;i++) if (str[i]!=null) {strr[x]=str[i];x++;}
            str=strr;
        }
}
